// utils/request.ts

import { BASE_URL, DEFAULT_HEADER, getToken } from './config';

interface RequestOptions<T> {
    url: string;
    method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
    data?: any;
    header?: Record<string, string>;
    timeout?: number;
}
type Data<T> = {
    code: string
    msg: string
    result: T
}

export const request=<T = any>(options: RequestOptions<T>)=>{
    const {
        url,
        method = 'GET',
        data = {},
        header = {},
        timeout = 10000,
    } = options;

    
    return new Promise<Data<T>>((resolve, reject) => {
        wx.request({
            url: BASE_URL + url,
            method,
            data,
            header: {
                ...DEFAULT_HEADER,
                ...header,
                //Authorization: getToken(), // 添加 token
            },
            timeout,
            success(res) {
                if (res.statusCode === 200) {
                    resolve(res.data as Data<T>);
                } else {
                    wx.showToast({ title: `错误 ${res.statusCode}`, icon: 'none' });
                    reject(res);
                }
            },
            fail(err) {
                wx.showToast({ title: '网络异常', icon: 'none' });
                reject(err);
            },
            complete(res) {
              console.log('complete', res)

              
            },
        });
    });
}
